package com.tnsw.facebookautoliker;

import java.util.ArrayList;

import org.json.JSONObject;

import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.StaticConfig;
import com.tnsw.coreutils.database.DBActionListener;
import com.tnsw.coreutils.database.RecordBase;
import com.tnsw.coreutils.ui.AdapterPullUpdate;
import com.tnsw.coreutils.ui.BitmapCache;
import com.tnsw.coreutils.ui.ListViewPullUpdate;
import com.tnsw.coreutils.ui.UpdateView;
import com.tnsw.facebookautoliker.base.FragmentBase;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.FriendsList;
import com.tnsw.facebookautoliker.helper.FacebookActionListener;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;
import com.tnsw.facebookautoliker.helper.command.FQLBase;
import com.tnsw.facebookautoliker.helper.command.FQLInterface;
import com.tnsw.facebookautoliker.helper.command.GetFriendsList;
import com.tnsw.facebookautoliker.helper.command.LikeManager;
import com.tnsw.facebookautoliker.services.AutoLikerService;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class FriendsListFragment extends FragmentBase implements ListViewDragActionListener, View.OnLongClickListener, OnItemClickListener, OnClickListener, DBActionListener, FacebookActionListener, FQLInterface {
	
	private LayoutInflater inflater = null;
	private Context context;
	private ViewGroup root; 
	
	private DBManager dbm;
	private GeneralManager gm;
	private FacebookBGManager fbm;
	
	private ListViewPullUpdate lv;
	private FriendListAdapter adapter;
	//private TextView tvHeader;
	private ViewGroup layoutFriendLists;
	private StandardUpdateView updateView;
	private ListViewDragExtender lvExtender;
	
	private int oldX = -1, oldY = -1, lastTopY = 0;
	private boolean isJustStarted = false;
	
	private LinearLayout layoutUpdateHost;
	
	private LikeManager lm;
	private String order = "";
	
	public FriendsListFragment() {
		super();
		this.tag = "FriendsListFragment";
		//this.setHasOptionsMenu(true);
		this.setVisibleMenu(new Integer[] {R.id.menu_mainscreen_logout, R.id.menu_mainscreen_ilikemost, R.id.menu_mainscreen_likememost, R.id.menu_search});
		Log.d(tag, "Constructor()");
				
	}
	
	@Override
	public void setBitmapCache(BitmapCache bmpCache) {
		super.setBitmapCache(bmpCache);
		if (this.adapter != null) {
			this.adapter.setBitmapCache(bmpCache);
		} else {
			MyLog.e(tag, "Cannot set bCache because adapter is null");
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		MyLog.d(tag, "onOptionsItemSelected");
		MainScreenActivity m = (MainScreenActivity) this.getActivity();
		boolean requiredRefresh = true;
		
		
		if (item.getItemId() == R.id.menu_mainscreen_likememost) {
			if (item.isChecked() == true) {
				item.setChecked(false);
				
			} else {
				item.setChecked(true);
				MenuItem m2 = m.getCurrentMenu().findItem(R.id.menu_mainscreen_ilikemost);
				m2.setChecked(false);
			}
		
		} else if (item.getItemId() == R.id.menu_mainscreen_ilikemost) {
			if (item.isChecked() == true) {
				item.setChecked(false);
				
			} else {
				item.setChecked(true);
				MenuItem m1 = m.getCurrentMenu().findItem(R.id.menu_mainscreen_likememost);
				m1.setChecked(false);
			}
			
		} else {
			requiredRefresh = false;
		}
		
		MenuItem mILikeMote = m.getCurrentMenu().findItem(R.id.menu_mainscreen_ilikemost);
		MenuItem mLikeMeMost = m.getCurrentMenu().findItem(R.id.menu_mainscreen_likememost);
		
		if (mILikeMote.isChecked() == true) {
			this.order = "like_count desc";
		} else if (mLikeMeMost.isChecked() == true) {
			this.order = "like_me_count desc";
		} else {
			this.order = "";
		}
		
		if (requiredRefresh) {
			this.adapter.refreshFromDB(this.order);
			this.adapter.notifyDataSetChanged();
			this.lv.smoothScrollToPosition(0);
		}
		
		return(false);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		MyLog.d(tag, "onCreateView(..)");
		
		if (this.getActivity() != null) {
			this.context = this.getActivity();
			this.dbm = DBManager.getInstance(context);
			this.gm = GeneralManager.getInstance();
			this.fbm = FacebookBGManager.getInstance(context);
			
			this.dbm.registerActionListener(this);
			this.fbm.registerActionListener(this);
			
		}
		
		this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.root = (ViewGroup) this.inflater.inflate(R.layout.fragment_friendslist, null);
		
		this.lv = (ListViewPullUpdate) this.root.findViewById(R.id.lv_fgfriendslist);
		this.layoutUpdateHost = (LinearLayout) this.root.findViewById(R.id.layoutUpdateHost);
		
		this.updateView = new StandardUpdateView(context, this.layoutUpdateHost);
		this.updateView.setListViewDragActionListener(this);
		
		this.layoutUpdateHost.addView(this.updateView.getView());
				
		this.layoutFriendLists = (ViewGroup) this.root.findViewById(R.id.layoutFriendLists);

		this.adapter = new FriendListAdapter(this.context, this.lv);
		this.adapter.setBitmapCache(this.bmpCache);
		
		//this.lv.addHeaderView((new FriendListUpdateView(context)).getView());
		this.lv.setAdapter(this.adapter);
		
		this.lvExtender = new ListViewDragExtender(context, this.lv, this.layoutUpdateHost, this.adapter);

		this.lvExtender.setListViewDragInterface(this.updateView);
		this.lvExtender.setUpdateView(this.updateView);
		
		this.lv.setOnItemClickListener(this);		
		this.lv.setOnLongClickListener(this);
		this.lv.setLongClickable(true);

		MyLog.d(tag, "isLongClickable=" + this.lv.isLongClickable());
		
		this.layoutUpdateHost.setVisibility(View.GONE);
		MyLog.d(tag, "layoutTest1 is GONE!");
		
		return(this.root);
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		//MyLog.d(tag, "onItemClick: top=" + this.lv.getTop() + ", left=" + this.lv.getLeft());
		MyLog.d(tag, "onItemClick: arg2=" + arg2 + ", arg3=" + arg3);

		/*
		this.setVisibleMenu(new int[] {R.id.menu_mainscreen_logout, R.id.menu_mainscreen_dumptasks, R.id.menu_search});
		MyLog.d(tag, "R.id.menu_mainscreen_logout=" + R.id.menu_mainscreen_logout);
		this.refreshOptionsMenu();
		*/
		
		/*
		TranslateAnimation aa = new TranslateAnimation(0, 0, 0, 500);
		aa.setDuration(1000);
		aa.setFillAfter(true);
		this.lv.startAnimation(aa);
		*/
		
		//this.layoutTest1.setVisibility(View.GONE);
		
		FriendsList fl = (FriendsList) this.adapter.getItem(arg2);
		if (fl != null) {
			MyLog.d(tag, "ClickedOn: " + fl.name + ", id=" + fl.id);
						
			String id = fl.id;
			
			FQLBase fqlb = new FQLBase(context, "SELECT likes, attachment, created_time, description, message, type, app_id, attachment, message, post_id, actor_id FROM stream WHERE source_id='" + id + "'", null);
			fqlb.setTag("name", fl.name);
			fqlb.setMaxRecord(1);
			fqlb.setFQLInterface(this);
			fqlb.setPagingColumn(null);
			fqlb.setParentFragmentBase(this);
			
			//fqlb.execute();
			//StaticConfig.DEBUGMODE = true;
			this.gm.addNewQueue(fqlb, 2);
			
		}
		
		//this.adapter.notifyDataSetChanged();
		
	}
	
	@Override
	public void onTabSelected() {
		super.onTabSelected();
		
		if (this.adapter != null) {
			if (this.adapter.getCount() < 2) {
				this.adapter.refreshFromDB(this.order);
				
			}
				
			this.adapter.notifyDataSetChanged();
		}
		
	}
	
	public void gotoPosition(int position) {
		if (position == -1) return;
		
		//this.lv.smoothScrollToPosition(position);
		this.lv.setSelection(position);
	}
	
	public int getPositionFromName(String name) {
		int position = -1;
		
		if (this.adapter != null) {
			position = this.adapter.getPositionByName(name);	
		} else {
			MyLog.e(tag, "adapter is null!!");
		}
		
		return(position);
	}
	
	@Override
	public void onClick(View v) {
		/*
		if (v == this.tvHeader) {
			this.tvHeader.setHeight(0);
			this.lv.setSelection(0);
		}
		*/

		
	}
	
	public void notifyDataChanged() {
		this.adapter.refreshFromDB(this.order);
		
		if (this.context != null) {
			Activity a = (Activity) this.context;
			a.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					adapter.notifyDataSetChanged();
					
				}
			});
		} else {
			MyLog.e(tag, "notifyDataChanged() - cnanot do, context is null");
		}
	}

	@Override
	public void onRecordAffected(String action, String tableName, int primaryKey, RecordBase record) {
		//MyLog.d(tag, "action=" + action + ", tableName=" + tableName);
		
		AutoLikerService aService = AutoLikerService.getInstance();
		
		if (action.equals("insert")) {
			if (record instanceof FriendsList) {
				final FriendsList fl = (FriendsList) record;
				
				Activity a = (Activity) this.context;
				a.runOnUiThread(new Runnable() 
				{	public void run() 
					{
						int position = adapter.updateRecord(fl);
						MyLog.d(tag, "insert-position=" + position);
					
						adapter.notifyDataSetChanged();					
					}
				});
				
				/*
				int position = this.adapter.updateRecord((FriendsList) record);
				MyLog.d(tag, "insert-position=" + position);
				
				this.adapter.notifyDataSetChanged();
				*/
				if (aService != null) {
					aService.updateFriendsList(fl.id, fl);
				}
			}
					
		} else if (action.equals("delete")) {
			if (record instanceof FriendsList) {
				FriendsList fl = (FriendsList) record;
				
				this.adapter.refreshFromDB(this.order);
				this.adapter.notifyDataSetChanged();
				
				if (aService != null) {
					aService.getHashFriendsList().remove(fl.id);
				}
			}
			
			
		} else if (action.equals("update")) {
			if (record instanceof FriendsList) {
				final FriendsList fl = (FriendsList) record;
				
				Activity a = (Activity) this.context;
				
				a.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						MyLog.d(tag, "updating..");
						adapter.updateRecordById(fl.id, fl);
						adapter.notifyDataSetChanged();						
					}
				});
				

				
				if (aService != null) {
					aService.updateFriendsList(fl.id, fl);
				}
			}
			
		}
		
	}

	@Override
	public void onRequestCompleted(Object sender, FacebookCommandObject fbco, int statusCode, Exception tr) {
		//MyLog.d(tag, "onRequestCompleted(" + fbco.getClass().getName() + ")");
		if (fbco instanceof GetFriendsList)  {
			this.updateView.hideLayout();
		}
	}
		
	@Override
	public void onDetach() {
		super.onDetach();
		
		//this.fbm.unregisterActionListener(this.updateView);
	}

	@Override
	public boolean onLongClick(View v) {
		MyLog.d(tag, "onLongClick()");
		return (true);
	}

	@Override
	public boolean onSingleRecordFetched(Object sender, int recordNo, JSONObject jo) {
		FQLBase fqlb = (FQLBase) sender;
		String name = (String) fqlb.getTag("name");
		//this.lm.doLike(jo, name);
		
		return(false);
	}

	@Override
	public void onEndQuery(Object sender, ArrayList<JSONObject> arrJ) {
		
	}

	@Override
	public void onUpdating(StandardUpdateView stdUpdateView) {
	
		GetFriendsList gfl = new GetFriendsList(this.context, true);
		gfl.execute();
	}

	@Override
	public void onCancelled(StandardUpdateView stdUpdateView) {
		
	}

		
}
